<?php

$_POST['name'] = sha1($_POST['name']);
$file = "../../../../uploads/message/$_POST[name]";

ini_set('auto_detect_line_endings',TRUE); //Check keyword /n or /r in MAC OS and WINDOWS, LINUX
if (fopen($file, 'r')) {
    $file_handle = fopen($file, 'r');
    setlocale(LC_ALL, 'Ja_JP.Shift_JIS');
    while (!feof($file_handle)) {
        $line = fgetcsv($file_handle, 1024);
        //$line_of_text[] = fgetcsv($file_handle, 1024,',');
        if(count($line) > 1){
            $line_of_text[] = $line;
        }else{
            $line = explode(';', $line[0]);
            $line_of_text[] = $line;
       }
    }
    $data = "";
    foreach ($line_of_text as $key => $value) {
        if (count($value) == 1) {
            unset($line_of_text[$key]);
            continue;
        }
        foreach($value as $k=>$v){
            $data[$key][$k] = iconv ("SJIS", "UTF-8" , $v ); //SJIS => UTF-8 before insert Database
        }
    }
    
    // dong ket noi doc file
    fclose($file_handle);
    
    // xu ly mang sau khi da doc
    array_shift($data);
    
    $list = array();
    foreach($data as $row){
        $list[$row[2]][] = $row[0].'_'.$row[1];
    }
    
    unlink($file);

    echo json_encode($list);            
}


//echo 0; // file csv khong ton tai


/*
$filename = "../../../../uploads/message/$_POST[name]";
//echo $filename;
    if (($handle = fopen($filename, "r")) !== FALSE) {
    $list = array();
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $list[$row[2]][] = $row[0].'_'.$row[1];
    }
    fclose($handle);
    }
    array_shift($list);
    
    unlink($filename);
    
    echo json_encode($list);
    //echo 0; // file csv khong ton tai
*/
